package com.hwl.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.hwl.commonutils.exception.GuliException;
import com.hwl.commonutils.result.ResultCodeEnum;
import com.hwl.oss.service.FileService;
import com.hwl.oss.util.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private OssProperties ossProperties;

    @Override
    public String uploadAvatar(MultipartFile file, String module) {
        String endpoint = ossProperties.getEndpoint();
        String keyid = ossProperties.getKeyid();
        String keysecret = ossProperties.getKeysecret();
        String bucketname = ossProperties.getBucketname();

        try {
            //创建OssClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
            //如果不存在，则先创建并设置公共读权限
            if (!ossClient.doesBucketExist(bucketname)) {
                ossClient.createBucket(bucketname);
                ossClient.setBucketAcl(bucketname, CannedAccessControlList.PublicRead);
            }

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件原始名称
            String fileName = file.getOriginalFilename();
            //把文件按照日期进行分类
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //构建文件上传路径
            String key = module + "/" + datePath + "/" +
                    //在文件名称里面添加随机唯一的值
                    UUID.randomUUID().toString().replaceAll("-", "") +
                    fileName;

            //上传文件流
            ossClient.putObject(bucketname, key, inputStream);
            log.info("文件上传成功！");
            // 关闭OSSClient
            ossClient.shutdown();

            //返回图片URL
            return "https://" + bucketname + "." + endpoint + "/" + key;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @Override
    public void removeFile(String url) {
        String endpoint = ossProperties.getEndpoint();
        String keyid = ossProperties.getKeyid();
        String keysecret = ossProperties.getKeysecret();
        String bucketname = ossProperties.getBucketname();

        //创建OssClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);

        //删除文件
        String host = "https://" + bucketname + "." + endpoint + "/";
        String objectName = url.substring(host.length());
        ossClient.deleteObject(bucketname, objectName);
        log.info("文件删除成功！");

        ossClient.shutdown();
    }
}
